package com.kerbores.blog.module;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.annotation.Views;
import org.nutz.mvc.ioc.provider.ComboIocProvider;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.kerbores.blog.bean.Article;
import com.kerbores.blog.bean.Article.ACL;
import com.kerbores.blog.bean.User;
import com.kerbores.blog.bean.User.Level;
import com.kerbores.blog.bean.User.Sex;
import com.kerbores.blog.module.common.BaseModule;
import com.kerbores.blog.service.IUserService;
import com.kerbores.blog.setup.InitSetUp;
import com.kerbores.utils.db.dao.IBaseDao;
import com.kerbores.utils.entries.Result;
import com.kerbores.utils.file.Images;
import com.kerbores.utils.template.velocity.VelocityViewMaker;

/**
 * @author 贵源 <br>
 *         create at 2014年10月18日
 */
@Modules(scanPackage = true)
@IocBy(type = ComboIocProvider.class, args = { "*org.nutz.ioc.loader.json.JsonLoader", "ioc.js", "*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "com.kerbores.blog" })
@Ok("json")
@Views({ VelocityViewMaker.class })
@SetupBy(InitSetUp.class)
public class MainModule extends BaseModule {

	@Inject
	private Dao dao;
	@Inject
	private IUserService userService;

	private String[] allowedUpload = { ".jpg", ".png", ".gif", ".bpm", ".jpeg" };

	@At("/")
	@Ok("forward:/article/list")
	public Result main() {
		return Result.success();
	}

	@At("/uploadFile")
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
	public NutMap upload(String dir, @Param("imgFile") TempFile file) {
		String absPath = "upload" + File.separator + (dir == null ? "Kerbores" : dir) + File.separator + Times.now().getTime() + file.getMeta().getFileExtension();
		String fileType = file.getMeta().getFileExtension();
		List<String> allowed = Arrays.asList(allowedUpload);
		Collections.sort(allowed);
		if (Collections.binarySearch(allowed, fileType) < 0) {
			data.put("error", 1);
			data.put("message", "不允许上传的类型 '" + fileType + "' ");
			return NutMap.WRAP(data);
		}

		File target = new File(Mvcs.getServletContext().getRealPath("/") + File.separator + absPath);
		try {
			Files.copy(file.getFile(), target);
		} catch (Exception e) {
			data.put("error", 1);
			data.put("message", e.getMessage());
		}
		data.put("error", 0);
		data.put("message", "上传成功");
		data.put("url", _base() + File.separator + absPath);
		return NutMap.WRAP(data);
	}

	@At("/uploadimage")
	public Result uploadimage(HttpServletRequest request) {
		System.err.println(Json.toJson(request.getParameterMap()));
		return Result.success();
	}

	@At("/403")
	@Ok("jsp:/403")
	public Result _403() {
		return Result.success();
	}

	@At("/init")
	public Result init() {
		log.info("初始化博客开始....");
		for (String bean : Mvcs.getIoc().getNames()) {
			if (bean.contains("Dao")) {
				IBaseDao dao = Mvcs.getIoc().get(IBaseDao.class, bean);
				dao.createTable();
			}
		}
		User user = new User();
		if (dao.query(User.class, null).isEmpty()) {
			// 初始化用户
			log.info("初始化用户....");
			user.setUserName("admin");
			user.setPassword(Lang.md5("admin"));
			user.setAge(28);
			user.setBirthDay(Times.D("1986-06-13"));
			user.setEmail("kerbores@gmail.com");
			user.setHomePage("http://blog.kerbores.com");
			user.setLastLoginBrowser("Chrome");
			user.setLastLoginIp("127.0.0.1");
			user.setLastLoginOs("MAC_OS");
			user.setLevel(Level.ADMIN);
			user.setMobile("18580649485");
			user.setMsn("wkipy@hotmail.com");
			user.setQq("19754300");
			user.setRealNanme("Kerbores");
			user.setSex(Sex.MALE);
			dao.insert(user);
		}
		if (dao.query(Article.class, null).isEmpty()) {
			Article article = new Article();
			article.setAcl(ACL.PUBLIC);
			article.setAuthorId(user.getId());
			article.setCatalogId(1);
			article.setContent("Hello world!");
			article.setIp("127.0.0.1");
			article.setSummary("Hello world");
			article.setTagInfo(null);
			article.setTitle("Hello world");
			article.setTop(true);
			article.setViewCount(0);
			dao.insert(article);
		}

		log.info("初始化博客结束....");
		return Result.success();
	}

	@At("/getPic")
	@Ok("jsp:/picShow")
	public Result getPic(String base) {
		String absPath = "gen" + File.separator + System.nanoTime() + ".png";
		File target = new File(Mvcs.getServletContext().getRealPath("/") + File.separator + absPath);
		Images.GenerateImage(base, target);
		data.put("path", _base() + File.separator + absPath);
		return Result.success(data);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.blog.module.common.BaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return "main";
	}

}
